package com.qf.myschool.servlet;

import com.qf.myschool.entity.Student;
import com.qf.myschool.service.IStudentService;
import com.qf.myschool.service.impl.StudentServiceImpl;
import com.qf.myschool.tool.PageTool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 老师的操作的Servlet
 */
@WebServlet("/TeacherServlet")
public class TeacherServlet extends FatherServlet {
	private static final long serialVersionUID = 1L;

	//继承FatherServlet中service,service方法中根据请求方法反射对象调用方法

	/**
	*创建学生数据访问对象
	*/
	IStudentService stuService=new StudentServiceImpl();

	/**
	*带个标记跳转到学生添加页面
	*@param request, response
	*@return void
	*/
	private String add(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException{
		request.setAttribute("flag", "add");
		return "register.jsp";
	}

	/**
	 * 删除学生信息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private String delStudentByName(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException{
		/*1.接收请求中数据*/
		String uname=request.getParameter("uname");
		
		/*调用相应业务层处理请求,并接收结果*/
		int result=stuService.delStudentByName(uname);

		//第二种ajax删除学生,第一个参数要删除的学生姓名,第二个参数是当前页面,
		// 在后台将学生删除成功后,调用分页查询当前页的数据,当前页码在请求对象中
		return "TeacherServlet?method=allStudent";
		//allStudent(request,response);


		//第一种ajax删除学生,第一个参数要删除的学生姓名,第二个参数是删除的按纽节点对象
		/*3.将删除的结果响应给ajax引擎对象*/
		//response.getWriter().write(String.valueOf(result));
	}

	/**
	 * ajax分页查询所有学生信息
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private String allStudent(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//1.接收ajax请求中数据,省略
		String currpage=request.getParameter("currpage");//传过来页码
		//初始化分页工具类的对象的属性
		PageTool p1=new PageTool();

		/*2.调用相应业务层处理请求,用变量接收处理结果*/
		List<Student> stus=stuService.queryStudent(p1,currpage);

		//3.根据页码来选择相应的页面跳转
		//将所有学生信息存请求对象中
		request.setAttribute("stuList", stus);
		//将分页对象中信息存在请求对象中
		request.setAttribute("page1",p1);
		if (currpage==null){//从首页跳转过来,默认在学生展示页面显示第一页
			//request.getRequestDispatcher("studentList.jsp").forward(request, response);
			return "studentList.jsp";
		}else{//点击页码的ajax请求,返回模板页面
			/*3.将结果返回给ajax引擎对象*/
			//将数据在模板页面显示,再将模板页面编译成嵌入数据的html页面,将嵌入数据的html页面返回给ajax引擎对象
			//request.getRequestDispatcher("modleList.jsp").forward(request, response);
			return "modleList.jsp";
		}
	}


}
